package utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;

public class SerializeHelper
{
	public static Object GetObjectFromString(String text)
	{
		Object instance = null;
		try
		{
			byte[] array=Base64.decode(text);
			
			ByteArrayInputStream myStream = new ByteArrayInputStream(array);
			ObjectInputStream s = new ObjectInputStream(myStream);
			instance = s.readObject();
		}
		catch (Exception exc)
		{
			exc.printStackTrace();
		}

		return instance;
	}

	public static String GetStringFromObject(Object instance)
	{
		String result = "";
		try
		{
			ByteArrayOutputStream myStream = new ByteArrayOutputStream();
			ObjectOutputStream s = new ObjectOutputStream(myStream);
			s.writeObject(instance);
			result = Base64.encode(myStream.toByteArray());
		}
		catch (Exception exc)
		{
			exc.printStackTrace();
		}
		return result;
	}

	public static void SendObjectToFile(Object obj, String filename)
	{
		try
		{
			String content = SerializeHelper.GetStringFromObject(obj);
			File file = new File(filename);
			FileWriter writer = new FileWriter(file);
			BufferedWriter bufferedWriter = new BufferedWriter(writer);
			bufferedWriter.write(content);
			bufferedWriter.close();
			writer.close();
		}
		catch (Exception exc)
		{
			exc.printStackTrace();
		}

	}

	public static Object GetObjectFromFile(String filename)
	{
		Object instance = null;
		try
		{

			File file = new File(filename);
			FileReader reader = new FileReader(file);
			BufferedReader bufferedReader = new BufferedReader(reader);
			String content = bufferedReader.readLine();
			bufferedReader.close();
			reader.close();
			instance = GetObjectFromString(content);
		}
		catch (Exception exc)
		{
			exc.printStackTrace();
		}
		return instance;
	}

}
